#!/usr/bin/env bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source $DIR/../../lib/shell/common.sh
source $DIR/../../lib/shell/env.sh

function set_channels(){
    # show max
    echo "==========set channels=========="
    max=$(ethtool -l $interface | grep -m 1 Combined | awk '{print $2}')
    echo $max
    # set max
    for ((i=1; i<=$max; i++)); do
        echo "$i"
        ethtool -L $interface combined $i
        if  [ $? -ne 0 ]; then
            return 1
        fi
        sleep 3
        ethtool -l $interface
    done
    return 0

}

function client_run() {
    echo "==========start client connect=========="
    iperf3 -t $IPERF3_RUNTIME -i $IPERF3_INTERVAL -P $IPERF3_PROCESS_NUM -f g -c $lts_ip > $IPERF3_LOG 2>&1 &
    if ps -ef|grep iperf3|grep -v grep && [ $? -eq 0 ];then
        return 0
    fi
    return 1
}

function server_kill() {
    echo "==========server kill...=========="
    server_down="kill -9 \`pidof iperf3\` &>/dev/null"
    if $ESSH $lts_ip pidof iperf3 &>/dev/null;then
        $ESSH $lts_ip $server_down && return 0 || return 1
    fi
}

function server_run() {
    echo "==========start server listen=========="
    server_kill
    server_cmd="iperf3 -sD"
    $ESSH $lts_ip $server_cmd &
    sleep 1
    if $ESSH $lts_ip ps -ef |grep "iperf3 -sD"; then
        echo "server listen success"
        return 0
    else
        echo "server listen failed"
        return 1
    fi
}

function check_iperf_results(){
    echo "==========check iperf3 results...=========="
    if test ! -f "$IPERF3_LOG"; then
        echo "iperf3 client log does not exist"
        return 1
    fi

    cat $IPERF3_LOG
    content=$(cat $IPERF3_LOG )
    rm -rf $IPERF3_LOG
    [ -n "$content" ] || { echo "iperf3 client error ";return 1; }
    if echo $content |grep -wq "iperf3: error"; then
        echo -e "iperf3 client error"
        return 1
    fi

    return 0
}

function channel_combined_test(){

    IPERF3_LOG=channel_combined_log.iperf3

    [ -z "$LTS_IPADDRESS" ] && { echo "Error: LTS IP are required, but none are given";exit 1; }
    lts_ip=$(echo $LTS_IPADDRESS | awk '{print $1}')

    server_run || return 1

    if ps -ef|grep iperf3|grep -v grep >/dev/null 2>&1;then
        kill -9 `ps -ef|grep iperf3|awk '{print $2}'`
    fi

    client_run || return 1
    sleep 5

    [ -n "$INTERFACES" ] || { echo "no interface found";return 1; }
    for interface in $INTERFACES;do
        set_channels || return 1
    done

    if ps -ef|grep iperf3|grep -v grep >/dev/null 2>&1;then
        kill `ps -ef|grep iperf3|awk '{print $2}'`
    fi

    server_kill || return 1
    check_iperf_results || return 1

    return 0
}

# # # # # # # # main # # # # # # # #
print_test_info "Network"
bash ../../../utils/sshconf.sh setup
trap "bash ../../../utils/sshconf.sh restore" EXIT
stress_network_env 1 $RUNTIME
channel_combined_test && test_pass || test_fail